package com.pn.taikao.service.impl;

import com.pn.taikao.entity.Answer;
import com.pn.taikao.entity.Exam;
import com.pn.taikao.entity.PaperQuestion;
import com.pn.taikao.mapper.AnswerMapper;
import com.pn.taikao.mapper.ExamMapper;
import com.pn.taikao.service.AnswerService;
import com.pn.taikao.service.PaperQuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class AnswerServiceImpl implements AnswerService {

    private final AnswerMapper answerMapper;
    private final ExamMapper examMapper;
    private final PaperQuestionService paperQuestionService;

    public AnswerServiceImpl(AnswerMapper answerMapper, ExamMapper examMapper, PaperQuestionService paperQuestionService) {
        this.answerMapper = answerMapper;
        this.examMapper = examMapper;
        this.paperQuestionService = paperQuestionService;
    }

    @Override
    @Transactional
    public void saveOrUpdateAnswer(Long examId, Long questionId, String content) {
        Answer existingAnswer = answerMapper.selectByExamIdAndQuestionId(examId, questionId);
        LocalDateTime now = LocalDateTime.now();
        
        if (existingAnswer != null) {
            // 更新现有答案
            existingAnswer.setContent(content);
            existingAnswer.setUpdateTime(now);
            answerMapper.update(existingAnswer);
        } else {
            // 创建新答案
            Answer answer = new Answer();
            answer.setExamId(examId);
            answer.setQuestionId(questionId);
            answer.setContent(content);
            answer.setScore(BigDecimal.ZERO);
            answer.setTeacherComment("");
            answer.setCreateBy("student");
            answer.setCreateTime(now);
            answer.setUpdateTime(now);
            answerMapper.insert(answer);
        }
    }

    @Override
    public Answer getByExamIdAndQuestionId(Long examId, Long questionId) {
        return answerMapper.selectByExamIdAndQuestionId(examId, questionId);
    }

    @Override
    public List<Answer> getByExamId(Long examId) {
        return answerMapper.selectByExamId(examId);
    }

    @Override
    @Transactional
    public void autoScore(Long examId, Long questionId, String studentAnswer, String correctAnswer, String questionType) {
        Answer answer = answerMapper.selectByExamIdAndQuestionId(examId, questionId);
        if (answer == null) {
            return;
        }

        BigDecimal score = BigDecimal.ZERO;
        
        // 根据题型进行自动评分
        if ("single".equals(questionType) || "judge".equals(questionType)) {
            // 单选题和判断题：答案完全一致
            if (studentAnswer != null && studentAnswer.trim().equalsIgnoreCase(correctAnswer != null ? correctAnswer.trim() : "")) {
                score = getQuestionScore(examId, questionId);
            }
        } else if ("multiple".equals(questionType)) {
            // 多选题：答案集合完全一致
            List<String> studentAnswers = parseMultipleAnswer(studentAnswer);
            List<String> correctAnswers = parseMultipleAnswer(correctAnswer);
            if (studentAnswers != null && correctAnswers != null && 
                studentAnswers.size() == correctAnswers.size() &&
                studentAnswers.containsAll(correctAnswers)) {
                score = getQuestionScore(examId, questionId);
            }
        } else if ("fill".equals(questionType)) {
            // 填空题：答案完全一致（忽略大小写和空格）
            if (studentAnswer != null && correctAnswer != null) {
                String normalizedStudent = studentAnswer.trim().toLowerCase();
                String normalizedCorrect = correctAnswer.trim().toLowerCase();
                if (normalizedStudent.equals(normalizedCorrect)) {
                    score = getQuestionScore(examId, questionId);
                }
            }
        }
        // essay类型的主观题需要教师手动评分，不进行自动评分

        answer.setScore(score);
        answer.setUpdateTime(LocalDateTime.now());
        answerMapper.update(answer);
    }

    @Override
    @Transactional
    public void setScore(Long examId, Long questionId, BigDecimal score, String teacherComment) {
        Answer answer = answerMapper.selectByExamIdAndQuestionId(examId, questionId);
        if (answer == null) {
            return;
        }
        answer.setScore(score);
        answer.setTeacherComment(teacherComment != null ? teacherComment : "");
        answer.setUpdateTime(LocalDateTime.now());
        answerMapper.update(answer);
    }

    /**
     * 解析多选题答案（逗号分隔）
     */
    private List<String> parseMultipleAnswer(String answer) {
        if (answer == null || answer.trim().isEmpty()) {
            return new ArrayList<>();
        }
        return Arrays.asList(answer.split(","));
    }

    /**
     * 获取题目在试卷中的分值
     */
    private BigDecimal getQuestionScore(Long examId, Long questionId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            return BigDecimal.ZERO;
        }
        
        PaperQuestion paperQuestion = paperQuestionService.getByPaperIdAndQuestionId(exam.getPaperId(), questionId);
        if (paperQuestion != null && paperQuestion.getScore() != null) {
            return BigDecimal.valueOf(paperQuestion.getScore());
        }
        
        return BigDecimal.ZERO;
    }
}

